package org.minuframework.file;

import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.minuframework.encrypt.Base64Utils;
import org.minuframework.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class DefaultFileUploader extends FileUploaderBase {

    // private static Logger logger = LoggerFactory.getLogger(PiecewiseFileUploader.class);

    public static final String POST_METHOD = "POST";

    public DefaultFileUploader() {}

    public DefaultFileUploader(HttpServletRequest request) {
        if (isMultipartContent(request)) {
            this.request = (MultipartHttpServletRequest) request;
        }
    }

    public static boolean isMultipartContent(HttpServletRequest request) {
        if (!StringUtils.equals(POST_METHOD, request.getMethod())) {
            return false;
        }
        return FileUploaderBase.isMultipartContent(new ServletRequestContext(request));
    }

    public DefaultFileUploader(MultipartFile multipartFile, File target) {
        this.multipartFile = multipartFile;
        this.target = target;
    }

    public DefaultFileUploader(File upload, File target) {
        this.upload = upload;
        this.target = target;
    }

    public DefaultFileUploader(String imgstr, File target) {
        this.imgstr = imgstr;
        this.target = target;
    }

    /**
     * 文件上传
     * 
     * @return String
     * @throws IOException
     */
    public String copy() throws IOException {
        if (this.multipartFile != null) {
            File realPath = buildPath(FileUtils.suffix(multipartFile.getOriginalFilename()));
            FileUtils.copy(multipartFile, realPath);
            return realPath.toString();
        } else if (this.upload != null) {
            File realPath = buildPath(FileUtils.suffix(upload.getName()));
            FileUtils.copy(upload, realPath);
            return realPath.toString();
        } else {
            throw new IOException("Cannot found output path from " + this.target);
        }
    }

    /**
     * base64生成文件
     * 
     * @return String
     * @throws IOException
     */
    public String generateImage() throws IOException {
        File realPath = buildPath(Base64Utils.suffix(imgstr));
        return Base64Utils.generateImage(imgstr, realPath) ? realPath.toString() : null;
    }

    /**
     * 获取文件输出路径
     * 
     * @param suffixName 后缀名
     * @return File
     * @throws IOException
     */
    public File buildPath(String suffixName) throws IOException {
        if (isFile()) {
            File realpath = this.target;
            int i = 1;
            while (realpath.exists()) {
                String parent = realpath.getParent();
                String name = realpath.getName().substring(0, realpath.getName().lastIndexOf("."));
                realpath = new File(parent, name + "(" + i + ")" + suffixName);
                i++;
            }
            return realpath;
        } else {
            File folder = new File(target, FileUtils.getFolderByMonth());
            FileUtils.isFile(folder);
            return FileUtils.buildPath(folder, prefix, 0, suffixName);
        }
    }

    /**
     * 检测目标路径是否包含文件名
     * 
     * @return boolean
     * @throws IOException
     */
    public boolean isFile() throws IOException {
        if (this.target == null) {
            throw new IOException("Cannot found output path from " + this.target);
        } else if (!this.target.isAbsolute()) {
            throw new IOException("Output path is not absolute path " + this.target);
        } else {
            return StringUtils.isNotEmpty(FileUtils.suffix(target.toString()));
        }
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

}
